<script setup name="MyEcharts">
import * as echarts from "echarts";
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { echartsResize } from "@/utils/echartsResize";

const echartsRef = ref(null);
const echartsInstance = ref(null);
const props = defineProps({
  options: {
    type: Object,
    require: true,
  },
  width: {
    type: String,
    require: true,
  },
  height: {
    type: String,
    require: true,
  },
});
const nowWidth = ref(props.width);
const nowHeight = ref(props.height);

onMounted(() => {
  echartsInit();
});

function echartsInit() {
  const myChart = echarts.init(echartsRef.value);
  echartsInstance.value = myChart;
  myChart.setOption(props.options, true);
  echartsResize(myChart);
}

watch(
  () => props.options,
  async (newVal) => {
    await nextTick();
    // console.log(echartsRef.value);
    echartsInstance.value.setOption(newVal, true);
  },
  {
    deep: true,
    immediate: true,
  }
);

watchEffect(() => {
  nowWidth.value = props.width;
});

watchEffect(() => {
  nowHeight.value = props.height;
});

onUnmounted(() => {
  echartsInstance.value.dispose();
});
</script>

<template>
  <div class="outer_echarts">
    <div
      class="echarts"
      :style="{ width: nowWidth, height: nowHeight }"
      ref="echartsRef"></div>
  </div>
</template>

<style lang="scss" scoped>
.outer_echarts {
  cursor: pointer !important;
}
</style>
